<template>
  <div class="app-container">

    <!-- <h2>
      {{textMap[dialogStatus]}}
    </h2> -->

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <div class="base-info clearfix">
        <el-form :rules="rules" ref="dataForm" :model="temp" label-width="110px" style='width:33%;' class="base-form">

          <el-form-item label="行政区域：" prop="adminstrativeArr">
            <el-cascader placeholder="请选择行政区域" v-model="temp.adminstrativeArr" :options="areaList.children" :props="{
                label: 'label',
                value: 'label'
              }" @change="handleCityChange">
            </el-cascader>
          </el-form-item>

          <el-form-item label="详细地址：" prop="address">
            <el-input v-model="temp.address" placeholder="请填写详细地址"></el-input>
          </el-form-item>

          <el-form-item label="公司名称：" prop="company">
            <el-input v-model="temp.company" placeholder="请填写公司名称"></el-input>
          </el-form-item>
          <!-- <el-form-item label="所在岗位" prop="job">
            <el-input v-model="temp.job" placeholder="请填写所在岗位"></el-input>
          </el-form-item> -->
          <el-form-item label="联系人姓名：" prop="username">
            <el-input v-model="temp.username" placeholder="请填写联系人姓名"></el-input>
          </el-form-item>

          <el-form-item label="联系电话：" prop="telephone">
            <el-input v-model="temp.telephone" placeholder="请填写联系电话"></el-input>
          </el-form-item>

          <el-form-item label="信用代码：" prop="creditCode">
            <el-input v-model="temp.creditCode" placeholder="请填写信用代码"></el-input>
          </el-form-item>

          <el-form-item label="排污许可：" prop="dischargePermit">
            <el-input v-model="temp.dischargePermit" placeholder="请填写排污许可"></el-input>
          </el-form-item>

          <el-form-item label="">
            <el-button v-if="dialogStatus=='create'" type="success" @click="createData" :loading="btnLoading">保存
            </el-button>
            <el-button v-if="dialogStatus=='update'" type="success" @click="updateData" :loading="btnLoading">保存
            </el-button>
            
            <el-button @click="goBack" :loading="btnLoading">返回</el-button>
          </el-form-item>

        </el-form>

        <!-- 地图区 -->


        <baidu-map class="baiduMap" :center="center" :zoom="zoom" @ready="handler" @click="getClickInfo">
          <bm-control :offset="{width: '10px', height: '10px'}">
            <bm-auto-complete v-model="keyword" :sugStyle="{zIndex: 1}">
              <el-input placeholder="请输入内容" v-model="keyword" clearable @clear="onChange">
              </el-input>
            </bm-auto-complete>
          </bm-control>
          <bm-local-search :keyword="keyword" :auto-viewport="true" :location="location"></bm-local-search>
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <bm-marker v-if="isEdit" :position="currentPosition" :dragging="true" animation="BMAP_ANIMATION_BOUNCE"  >
          </bm-marker>
        </baidu-map>

      </div>
    </el-card>

  </div>
</template>

<script>
  import { addSave, updateSave, getDetail } from '@/api/isp'
  import { mapGetters } from 'vuex'

  import areaList from '../../../static/json/area.json'

  export default {
    name: 'IspIndex',
    computed: {
      ...mapGetters([
        'token'
      ])
    },
    components: {
    },
    data() {
      return {
        isEdit: false,
        keyword: '',
        location: '',
        btnLoading: false,
        dialogStatus: 'create',
        textMap: {
          update: '编辑单位',
          create: '新建单位'
        },
        dialogVisible: false,
        temp: {
          username: '', // 联系人姓名
          adminstrativeArr: [],
          adminstrative: '', // 行政区域
          address: '', // 详细地址
          company: '', // 公司名称
          job: '', // 所在岗位
          telephone: '', // 联系电话
          creditCode: '', // 信用代码
          dischargePermit: '', // 排污许可
          userId: '', // 当前登录人ID
          longitude: ''//经纬度
        },
        rules: {
          username: [
            { required: true, message: '请填写联系人姓名', trigger: 'change' },
            { max: 50, message: '联系人姓名最大长度50位', trigger: 'change' }
          ],
          adminstrativeArr: [
            { required: true, message: '请选择行政区域', trigger: 'change' }
          ],
          address: [
            { required: true, message: '请填写详细地址', trigger: 'change' },
            { max: 255, message: '详细地址最大长度255位', trigger: 'change' }
          ],
          company: [
            { required: true, message: '请填写公司名称', trigger: 'change' }
          ],
          telephone: [
            { required: true, message: '请填写联系电话', trigger: 'change' }
          ],
          creditCode: [
            { required: true, message: '请填写信用代码', trigger: 'change' }
          ],
          dischargePermit: [
            { required: true, message: '请填写排污许可', trigger: 'change' }
          ]
        },
        listLoading: false,
        // 行政区域数据
        areaList,
        // 地图信息
        center: { lng: 0, lat: 0 },
        zoom: 3,
        handleId: '',
        restaurants: [],
        currentPosition: { lng: 0, lat: 0 }
      }
    },
    watch: {
      // 表单内容体
      temp: {
        handler: function(val, oldVal) {
          console.log('val :>> ', val)
          if (val.adminstrativeArr.length > 0) {
            this.location = val.adminstrativeArr[0]
          }
        },
        deep: true
      }
    },
    created() {
      this.temp.userId = this.token * 1
      // console.log(this.$route)
      // 如果是编辑获取id
      const id = this.$route.query.id || ''
      if (id !== '') {
        this.dialogStatus = 'update'
        this.handleId = id
        getDetail({
          id: this.handleId
        }).then(response => {
          this.temp = response.data
          if (this.temp.longitude !== '') {
            var position = this.temp.longitude.split(',')
            this.currentPosition = { lng: position[0] * 1, lat: position[1] * 1 }
            this.isEdit = true
            this.current = this.currentPosition
            this.zoom = 10
          }
          // 所在地区
          if (typeof this.temp.adminstrative !== 'undefined' && this.temp.adminstrative !== '') {
            this.temp.adminstrativeArr = this.temp.adminstrative.split('/')
          } else {
            this.temp.adminstrativeArr = []
          }
        }).catch(err => {
          err
        })
      }
    },
    activated() {
    },
    deactivated() {
    },
    methods: {
      onChange() {
        // if (e === '') {
        this.temp.longitude = ''
        // }
      },
      querySearch(queryString, cb) {
        var restaurants = this.restaurants
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      handleSelect(item) {
        console.log(item)
      },
      handler({ BMap, map }) {
        // console.log(BMap, map)
        this.center.lng = 116.404
        this.center.lat = 39.915
        this.zoom = 15
      },
      // 选择地区
      handleCityChange(value) {
      },
      /***
       * 地图点击事件。
       */
      getClickInfo(e) {
        console.log('经纬度 :>> ', e)
        this.temp.longitude = e.point.lng + ',' + e.point.lat
        // this.center.lng = e.point.lng
        // this.center.lat = e.point.lat
      },
      // 重置数据
      resetTemp() {
        this.temp = {
          username: '', // 联系人姓名
          adminstrativeArr: [],
          adminstrative: '', // 行政区域
          address: '', // 详细地址
          company: '', // 公司名称
          job: '', // 所在岗位
          telephone: '', // 联系电话
          creditCode: '', // 信用代码
          dischargePermit: '', // 排污许可
          userId: this.token * 1, // 当前登录人ID
          longitude: ''
        }
        return this.temp
      },
      // 新建 - 保存
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // if (this.temp.longitude === '') {
            //   this.$message.error('请选择单位地点')
            //   return
            // }
            // 所在地区
            if (this.temp.adminstrativeArr.length !== 0) {
              this.temp.adminstrative = this.temp.adminstrativeArr.join('/')
            } else {
              this.temp.adminstrative = ''
            }
            this.btnLoading = true
            addSave(this.temp).then(response => {
              this.btnLoading = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            }).catch(err => {
              this.btnLoading = false
              err
            })
          }
        })
      },
      // 编辑 - 保存
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 所在地区
            if (this.temp.adminstrativeArr.length !== 0) {
              this.temp.adminstrative = this.temp.adminstrativeArr.join('/')
            } else {
              this.temp.adminstrative = ''
            }
            this.btnLoading = true
            updateSave(this.temp).then(response => {
              this.btnLoading = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }).catch(err => {
              this.btnLoading = false
              err
            })
          }
        })
      },
  
      // 返回
      goBack() {
        this.$router.back()
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .base-form {
    width: 33%;
    float: left;
  }

  .baiduMap {
    float: left;
    height: 500px;
    width: 67%;
    padding-left: 20px;
  }
</style>